package com.fuze.questionnaire.controller;

import com.fuze.questionnaire.common.Advice;
import com.fuze.questionnaire.common.CustomException;
import com.fuze.questionnaire.common.Result;
import com.fuze.questionnaire.domain.dto.BasicUserInformationDTO;
import com.fuze.questionnaire.domain.entity.BasicUserInformation;
import com.fuze.questionnaire.domain.vo.LoginResultVO;
import com.fuze.questionnaire.domain.vo.LoginVO;
import com.fuze.questionnaire.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;

/**
 * @author sepc_
 * @date 10/20/2021 15:09
 * 用户登录Controller
 */
@RestController
@Slf4j
@Api(tags = "用户信息API")
@RequiredArgsConstructor
@Validated
public class UserInfoController {

    final UserInfoService userInfoService;

    @ApiOperation(value = "用户基本数据录入")
    @PostMapping("/info")
    public Result info(@ApiParam(value = "userInfo") @Valid @RequestBody BasicUserInformationDTO userInfo) {
        BasicUserInformation information = new BasicUserInformation();
        BeanUtils.copyProperties(userInfo, information);
        return Result.ok(userInfoService.insertOrUpdate(information));
    }

    @ApiOperation(value = "微信用户登录接口")
    @PostMapping(value = "/login")
    public Result login(@ApiParam(value = "loginVO")@ Valid @RequestBody LoginVO loginVO) {
        Optional<String> loginRes = userInfoService.login(loginVO.getCode());
        if (!loginRes.isPresent()) {
            throw new CustomException(Advice.FAILED_LOGIN);
        }
        return Result.ok(new LoginResultVO(
                loginRes.get(),
                userInfoService.checkUserExist(loginRes.get())
        ));
    }

    /**
     * 查询用户提交的信息
     * @return 用户已经提交的基本信息
     */
    @ApiOperation("根据openid查询用户的基本信息")
    @GetMapping("/info/{openid}")
    public Result listUserInfo( @PathVariable String openid){
        return Result.ok(userInfoService.listUserInfo(openid));
    }

}
